
// pages/detail/detail.js
var imgUrls = [];   //轮播图
var comment = [];
var talks = [];
var goods = null; //物品详情储存
var goodsId = null;
var id = null;
var parentId = null;
var replayerId = null;
var replayerName = null;
var app = getApp();
var pageSize = 30;  // 获取最大评论数
var commentNumber = 0;
var max = 0;

Page({
  /* 页面的初始数据*/
  data:{
    indicatorDots: true,       //是否显示面板指示点
    autoplay: true,       //是否自动切换
    interval: 3000,       //自动切换时间间隔
    duration: 1000,       //滑动动画时长
    inputValue: '',
  },


  //全局
  //输入框失去焦点时触发
  bindInputBlur:function(e){
    this.data.inputValue = e.detail.value;
  },


  //请求商品信息——商品详情
  goodsInfoShow:function (){
    var that = this;

    wx.request({
      url:app.globalData.urlPath + 'getGoodsById.action',
      method:'get',
      data:{id: goodsId},       //直接option获取

      success:function (res){ //返回成功
        var goodsItem = res.data;
        imgUrls = res.data.images.split(";");
        for(var i=0;i<imgUrls.length;i++){
          imgUrls[i] = app.globalData.imgPath + imgUrls[i];
        }
        goods = {
          //商品信息
          imgUrls:  imgUrls,
          title:    res.data.title,
          price:    res.data.price,
          goodsId:  res.data.id,
          text:     res.data.info,
          //卖家信息
          name: res.data.user,
          phone: res.data.userId,
        }
        //console.log(goods);
        that.setData({  //对goods操作，添加
          goods: goods,
        })
      },

      fail:function(err){ },//请求失败
      complete:function(){ },//请求完成后执行的函数
    })
  },


  //评论模块
  //日期转换——获取评论
  timestampToTime:function (timestamp){
    var date = new Date(timestamp);//时间戳为10位需*1000，时间戳为13位的话不需乘1000
    var Y = date.getFullYear() + '-';
    var M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '-';
    var D = date.getDate() + ' ';
    var h = date.getHours() + ':';
    var m = date.getMinutes() + ':';
    var s = date.getSeconds();
    return Y + M + D + h + m + s;
  },

  //递归遍历评论子树——获取评论
  //遍历评论单元
  oneNode:function(node, id){//node为当前评论节点（包括主评论+子评论）；id为主评论id
    var that = this;
    var Subcomment = null;
    Subcomment = {
      time:       that.timestampToTime(node.createTime),//时间
      avatar:     node.user.avatar,//评论者头像
      nickName:   node.user.nickName,//评论者昵称
      content:    node.content,//评论内容
      contentId:  node.user.id,//此评论人id
      parentId:   id,//主评论id
    }
    return Subcomment;
  },

  //递归遍历子评论——获取评论
  travel:function(node, Subcomment, j, id){
    if(node == null) return;
    Subcomment[j] = this.oneNode(node, id);
    if(node.subComment != null && node.subComment.length > 0){
      var i = 0;
      for(i=0;i<node.subComment.length;i++)
        this.travel(node.subComment[i], Subcomment, ++j, id);
    }
    return Subcomment;
  },

  //请求评论信息
  commentInfoShow:function (){
    var that = this;

    wx.request({
      url:app.globalData.urlPath + 'getCommentByGoodsId.action',
      method:'get',
      data: {goodsId:goodsId, pageSize},//goodid:2

      success:function(res){
        var commentItem = res.data;
        var i = 0;
        while(commentItem[i] != null){
          var j = 0;
          var Subcomment = [];//临时存储评论
          Subcomment = that.travel(commentItem[i], Subcomment, j, commentItem[i].id);//获取评论数组（主评+子评）
          Subcomment.splice(0, 1);//去掉主评论
          comment[i] = {
            //被回复者（上级）
            replayer: commentItem[i].replayer,
            //回复者（主体）
            userId:     commentItem[i].user.id,//id
            avatar:     commentItem[i].user.avatar,//头像
            nickName:   commentItem[i].user.nickName,//昵称
            time:       that.timestampToTime(commentItem[i].createTime),//创建时间
            content:    commentItem[i].content,//内容
            contentId:  commentItem[i].id,
            //留言者（下级）
            subComment:Subcomment,
          }
          //if(comment[i].contentId > max)
            //max = comment[i].content;
          i++
        }
        console.log(comment)
        that.setData({
          comment:comment,
        })
      },
      fail:function(err){ },//请求失败
      complete:function(){ }//请求完成后执行的函数
    })
  },

  //上传评论信息
  commentUpload:function(arr){
    var that = this;

    wx.request({
      url:app.globalData.urlPath + 'postComment.action',
      method:'post',
      header:{
        "Content-Type":"application/x-www-form-urlencoded"
      },
      data:{
        content:    arr[0].content,//评论内容
        parentId:   arr[0].parentId,//主评论id
        goodsId:    goodsId,              //this.goods.goodsId,//商品id
        replayerId: arr[0].replayerId,//回复评论（子评论）id
        rdSession:  app.globalData.rdSession,
      },

      success:function(res){
        console.log(res.data);
      },
      fail:function(err){ },//请求失败
      complete:function(){ }//请求完成后执行的函数
    })
  },

  // 加载评论数据
  loadTalks:function (){
    var that = this;
    var i = 0;
    //comment[i]在commentInfoShow中

    while(comment[commentNumber] != null){
      //只有talks才能在页面中更新
      talks.push({
        avatar:     comment[commentNumber].avatar,
        nickName:   comment[commentNumber].nickName,
        content:    comment[commentNumber].content,
        time:       comment[commentNumber].time,
        subComment: comment[commentNumber].subComment,
        contentId:  comment[commentNumber].contentId,
        replayer:   comment[commentNumber].replayer,
        userId:     comment[commentNumber].userId,
      })
      commentNumber++;
      i++;
      if(i>=5) break;
    }

    this.setData({
      talks:talks,
    })
  },

  //加载更多
  bindDownLoad:function(){
    console.log('加载更多')
    var that = this;
    var i = 0;
    //talks = [];
    //comment[i]在commentInfoShow中

    while(comment[commentNumber] != null){
      //只有talks才能在页面中更新
      talks.push({
        avatar:     comment[commentNumber].avatar,
        nickName:   comment[commentNumber].nickName,
        content:    comment[commentNumber].content,
        time:       comment[commentNumber].time,
        subComment: comment[commentNumber].subComment,
        contentId:  comment[commentNumber].contentId,
        replayer:   comment[commentNumber].replayer,
        userId:     comment[commentNumber].userId,
      })
      commentNumber++;
      i++;
      if(i>=5) break;
    }

    if(i<5){
      wx.showToast({ //如果全部加载完成了也弹一个框
        title: '我也是有底线的',
        icon: 'success',
        duration: 300
      });
      return false;
    }
    else{
      wx.showLoading({ //期间为了显示效果可以添加一个过度的弹出框提示“加载中”  
        title: '评论加载中',
        icon: 'loading',
      });
      setTimeout(() => {
        this.setData({
          talks:talks,
        })
        wx.hideLoading();
      }, 1500)
    }
  },

  //发布评论
  faBu:function(){
    var that = this;

    this.data.talks.unshift({
      parentId:   0,//父评论
      replayerId: 0,//回复者
      avatar:     app.globalData.userInfo.avatarUrl,
      nickName:   app.globalData.userInfo.nickName,
      content:    this.data.inputValue,
      time:       that.timestampToTime(Date.parse(new Date())),
      //replayer:   null,
      //contentId:  max + 1,
      //subcomment: [],
    })
    max++;
    this.commentUpload(this.data.talks);//上传
    wx.showToast({title:'发布成功'});
    this.setData({
      inputValue:'',
      talks:talks,
    })
  },

  //回复框
  showRespond:function(e){
    parentId = e.currentTarget.dataset.parent;//主评论id
    replayerId = e.currentTarget.dataset.replayer;//回复评论（子评论）id
    //console.log(e.currentTarget.dataset)
    if(replayerId != -1)
      replayerName = '@' + e.currentTarget.dataset.nickname + ':';//回复评论（子评论）昵称
    else
      replayerName = '';
    //console.log(replayerName);
    // 设置动画内容为：使用绝对定位显示区域，高度变为100%
    this.animation.bottom("0rpx").height("100%").step();
    this.setData({
      respondAnimationData: this.animation.export(),
    })
  },
  hideRespond:function() {
    // 设置动画内容为：使用绝对定位隐藏整个区域，高度变为0
    this.animation.bottom("-100%").height("0rpx").step();
    this.setData({
      respondAnimationData: this.animation.export(),
    })
  },

  //回复评论
  huifu:function(){
    var that = this;
    var index = 0;
    for(var i=0;i<pageSize;i++){
      if(talks[i].contentId == parentId){
        index = i;
        break;
      }
    }
    this.data.talks[index].subComment.unshift({
      parentId:   parentId,//父评论
      replayerId: replayerId,
      avatar:     app.globalData.userInfo.avatarUrl,
      nickName:   app.globalData.userInfo.nickName,
      content:    replayerName + this.data.inputValue,
      time:       that.timestampToTime(Date.parse(new Date())),
    })

    that.hideRespond();
    this.commentUpload(talks[index].subComment);//上传评论
    wx.showToast({title: '发布成功'});
    this.setData({
      inputValue:'',
      talks:talks,
    })
  },


  //卖家信息
  //联系卖家——卖家信息
  showMessage:function(){
    // 设置动画内容为：使用绝对定位显示区域，高度变为100%
    this.animation.bottom("0rpx").height("100%").step();
    this.setData({
      messageAnimationData:this.animation.export(),
    })
  },
  hideMessage:function(){
    // 设置动画内容为：使用绝对定位隐藏整个区域，高度变为0
    this.animation.bottom("-100%").height("0rpx").step();
    this.setData({
      messageAnimationData:this.animation.export(),
    })
  },


  //生命周期函数
  //物品信息
  /*** 生命周期函数--监听页面加载页面信息*/
  onLoad: function(options){
    var that = this;
    goodsId = options.goodsId;
    //获取评论信息
    this.loadTalks();//更新talks
    console.log(app.globalData.userInfo);
  },

  onShow:function(){
    var that = this;
    this.goodsInfoShow();
    this.commentInfoShow();
  },

  //评论内容
  /** * 生命周期函数--监听页面初次渲染完成 */
  onReady:function () {
    // 评论弹出层动画创建
    this.animation = wx.createAnimation({
      duration: 400, // 整个动画过程花费的时间，单位为毫秒
      timingFunction: "ease", // 动画的类型
      delay: 0, // 动画延迟参数
    })
    this.loadTalks();//更新talks
  },
})